<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2017/4/1
 * Time: 14:46
 */

namespace SDXApi\Service;


use SDXApi\Abstracts\TemplateAbstract;
use SDXApi\Listeners\LocationLinkSourceListener;
use SDXApi\Model\HomeTemplateStencilImageModel;

/**
 * Class HomeTemplateTransverseService
 * @package SDXApi\Service
 */
class HomeTemplateTransverseService extends TemplateAbstract
{
	/**
	 * @var HomeTemplateStencilImageModel
	 */
	protected $templateStencilImageModel;

	/**
	 * 注入实例
	 * HomeTemplateTransverseService constructor.
	 */
	public function __construct()
	{
		$this->templateStencilImageModel = new HomeTemplateStencilImageModel();
	}

	/**
	 * Created by Jerry
	 * @param array $stencil
	 * @param int $userId
	 * @param int $wid
	 * @return array
	 */
	public function handle($stencil = array(), $userId = 0, $wid = 8)
	{
        $source = $this->sourceApp();
        $cacheName = 'home_template_image_transverse_id_' . $stencil['id'] . '_app_' . $source;
        $images = $this->getCache($cacheName);

		if (empty($images)) {
			$images = $this->transverse($stencil);

			if (! empty($images)) {
				$this->cacheData($cacheName, $images, mt_rand(3200, 4200));
			}
		}

        if (isset($images['link_data']) && empty($images['link_data'])) {
            $images['link_data'] = new \stdClass();
        }

		return $images;
	}

	/**
	 * 处理图片数据
	 * Created by Jerry
	 * @param array $stencil
	 * @return array
	 */
	protected function transverse($stencil = array())
	{
		$images = $this->findTemplateStencilImageByStencilId($stencil['id']);

		if (count($images) > 1) {
			$images = self::checkDataSort($images);
		}

		$transverse = array(
			1	=>	'750px 260px',
		);

        $locationLinkListener = new LocationLinkSourceListener();
		foreach ($images as $key => $value) {

			if (empty($stencil['size'])) {
				$stencil['size'] = $value['size'];
				$stencil['size_message'] = $transverse[$stencil['size']];
			}

			if (!isset($stencil['transverse_image'])) {
				$stencil['transverse_image'] = $value['url'];
			}

            $link_data = $locationLinkListener->onCallLink($value['link']);
            if (! empty($link_data)) {
                $images[$key]['link_data'] = $link_data;
            }

			unset($images[$key]['size']);
		}

		$stencil['images_list'] = $images;

		return $stencil;
	}

	/**
	 * 查找图片
	 * Created by Jerry
	 * @param $stencilId
	 * @return mixed
	 */
	protected function findTemplateStencilImageByStencilId($stencilId)
	{
		return $this->templateStencilImageModel->find_template_stencil_images_by_stencil_id($stencilId);
	}
}